package net.kingborn.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileKit {
	
	/**
	 * 清空文件
	 * 
	 * @Description
	 * @param filePath
	 */
	public static void clearFile(String filePath) {
		File file = new File(filePath);
		if (file.exists()) {
			System.out.println("正在删除文件: " + filePath);
			System.gc();
			file.getAbsoluteFile().delete();
		}
	}

	/**
	 * 得到文件MD5
	 * 
	 * @Description
	 * @param filePath
	 *            文件路径
	 * @return
	 * @throws IOException 
	 * @throws NoSuchAlgorithmException 
	 */
	public static String getMD5(String filePath) throws IOException {

		File file = new File(filePath);
		if (!file.exists()) {
			throw new FileNotFoundException("文件不存在: [" + filePath + "]");
		}

		String value = null;
		FileInputStream in = null;
		try {
			in = new FileInputStream(file);
			MappedByteBuffer byteBuffer = in.getChannel().map(
					FileChannel.MapMode.READ_ONLY, 0, file.length());
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(byteBuffer);
			BigInteger bi = new BigInteger(1, md5.digest());
			value = bi.toString(16);

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			
		} finally {
			if (null != in) {
				try {
					in.close();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return value;
	}
	
}
